package com.fengye.serialization.serializer.impl;

import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fengye.serialization.common.FDateJsonDeserializer;
import com.fengye.serialization.common.FDateJsonSerializer;
import com.fengye.serialization.serializer.Serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.util.Date;

/**
 * @Author fengye
 * @Date 2023/2/13 9:20
 **/
public class JSONSerializer implements Serializer {

    private  static final ObjectMapper objectMapper = new ObjectMapper();
    static {
        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        SimpleModule mudole = new SimpleModule("DateTimeModule" + Version.unknownVersion());
        mudole.addSerializer(Date.class, new FDateJsonSerializer());
        mudole.addDeserializer(Date.class, new FDateJsonDeserializer());
    }

    @Override
    public <T> byte[] serialize(T obj) throws Exception {
        if (obj == null) {
            return new byte[0];
        }

        String json = objectMapper.writeValueAsString(obj);
        return json.getBytes();
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception {
        if(data == null) {
            return null;
        }
        String json = new String(data);
        return objectMapper.readValue(data, clazz);
    }


}
